{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 模型的保存\n",
    "\n",
    "当我们训练完一个模型之后，我们可以将其保存起来，留着下次用～\n",
    "\n",
    "这里我们以 LeNet 为例\n",
    "\n",
    "我们有一个训练好的 LeNet 我们需要保存，有两种方法：\n",
    "\n",
    "1、保存结构和参数\n",
    "\n",
    "```\n",
    "torch.save(model, PATH) # 保存模型的结构和参数\n",
    "\n",
    "model = torch.load(PATH) # 加载模型的结构和参数\n",
    "\n",
    "# PATH 为模型保存路径\n",
    "\n",
    "```\n",
    "\n",
    "2、仅保存参数\n",
    "\n",
    "``` \n",
    "torch.save(model.state_dict(), PATH) # 仅仅保存模型的参数\n",
    "\n",
    "model = ModelClass(*args, **kwargs) # 实例化模型\n",
    "model.load_state_dict(torch.load(PATH)) # 加载模型参数\n",
    "\n",
    "# PATH 为模型保存路径\n",
    "```\n",
    "\n",
    "解释一下： 对于pytorch而言，它内部每一层的参数，都会被保存在 model.state_dict() 字典中，这是一个有序字典，字典的 key 就是层的名字+ weight 或者 bias\n",
    "\n",
    "比如：第一层就是 \n",
    "\n",
    "> 'conv1.weight', 'conv1.bias'\n",
    "\n",
    "然后，我们在保存模型的时候，直接把这个字典保存起来。\n",
    "\n",
    "等到加载的时候，一层一层的遍历，把新模型的 conv1 层用我们保存好的模型参数进行替换。\n",
    "\n",
    "这就是为什么，我们仅仅保存权重的话，可以随意的对模型的结构进行更改，但是请注意**我们必须保证模型中各层的名字一致，不一致会报错**\n",
    "\n",
    "\n",
    "**推荐使用第二种保存方式，因为我们只保存参数的话，首先我们可以节省存储空间，其次加载速度也会更快，最后，我们可以对重新构建的模型进行微调，比如新增几层，或者删除几层**\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [],
   "source": [
    "import torch\n",
    "import torch.nn as nn\n",
    "\n",
    "class LeNet5(nn.Module):\n",
    "    def __init__(self, in_dim, n_class):\n",
    "        super(LeNet5, self).__init__()\n",
    "        self.conv1 = nn.Conv2d(in_dim, 6, 5, padding=2)\n",
    "        self.conv2 = nn.Conv2d(6, 16, 5)\n",
    "        self.fc1 = nn.Linear(16*5*5, 120)\n",
    "        self.fc2 = nn.Linear(120, 84)\n",
    "        self.fc3 = nn.Linear(84, n_class)\n",
    "        \n",
    "        # 参数初始化函数\n",
    "        for p in self.modules():\n",
    "            if isinstance(p, nn.Conv2d):\n",
    "                nn.init.xavier_normal(p.weight.data)\n",
    "            elif isinstance(p, nn.Linear):\n",
    "                nn.init.normal(p.weight.data)\n",
    "\n",
    "    # 向前传播\n",
    "    def forward(self, x):\n",
    "        x = F.max_pool2d(F.relu(self.conv1(x)), 2)\n",
    "        x = F.max_pool2d(F.relu(self.conv2(x)), 2)\n",
    "        x = x.view(-1, self.num_flat_features(x))\n",
    "        x = F.relu(self.fc1(x))\n",
    "        x = F.relu(self.fc2(x))\n",
    "        x = self.fc3(x)\n",
    "        return x\n",
    "    \n",
    "    def num_flat_features(self, x):\n",
    "        size = x.size()[1:]\n",
    "        num_features = 1\n",
    "        for s in size:\n",
    "            num_features *= s\n",
    "        return num_features\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 第一种：保存模型的参数和结构"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "/usr/local/lib/python3.5/dist-packages/torch/serialization.py:159: UserWarning: Couldn't retrieve source code for container of type LeNet5. It won't be checked for correctness upon loading.\n",
      "  \"type \" + obj.__name__ + \". It won't be checked \"\n"
     ]
    }
   ],
   "source": [
    "# 实例化模型\n",
    "lenet = LeNet5(224, 10)\n",
    "\n",
    "# 让我们假设，经过了一连串的训练\n",
    "# 这时候的模型已经被我们训练的\n",
    "# 十分完美了。\n",
    "\n",
    "PATH = \"./test.pkl\"\n",
    "\n",
    "torch.save(lenet, PATH)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "LeNet5(\n",
      "  (conv1): Conv2d(224, 6, kernel_size=(5, 5), stride=(1, 1), padding=(2, 2))\n",
      "  (conv2): Conv2d(6, 16, kernel_size=(5, 5), stride=(1, 1))\n",
      "  (fc1): Linear(in_features=400, out_features=120, bias=True)\n",
      "  (fc2): Linear(in_features=120, out_features=84, bias=True)\n",
      "  (fc3): Linear(in_features=84, out_features=10, bias=True)\n",
      ")\n"
     ]
    }
   ],
   "source": [
    "model = torch.load(PATH)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 第二种：仅保存模型的参数"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [],
   "source": [
    "torch.save(lenet.state_dict(), PATH)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {},
   "outputs": [],
   "source": [
    "model2 = LeNet5(224, 10) # 实例化模型\n",
    "model2.load_state_dict(torch.load(PATH)) # 加载模型参数"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "LeNet5(\n",
      "  (conv1): Conv2d(224, 6, kernel_size=(5, 5), stride=(1, 1), padding=(2, 2))\n",
      "  (conv2): Conv2d(6, 16, kernel_size=(5, 5), stride=(1, 1))\n",
      "  (fc1): Linear(in_features=400, out_features=120, bias=True)\n",
      "  (fc2): Linear(in_features=120, out_features=84, bias=True)\n",
      "  (fc3): Linear(in_features=84, out_features=10, bias=True)\n",
      ")\n"
     ]
    }
   ],
   "source": [
    "print(model2)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.5.2"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
